package com.idemon.ds.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.idemon.config.Consts;
import com.jfinal.kit.PropKit;

public class DataCache<E> {

	private static Map<String, DataBag> caches = new HashMap<String, DataBag>(0);

	public static <E> List<E> getData(String key,IDataQuery dataQuery) {
		DataBag<E> db = caches.get(key);
		List<E> result = null;
		if(db == null || db.isExpired()){
			result = dataQuery.queryData();
			putData(key, result);
		}else{
			result = db.getBeans();
		}
		return result;
	}
	
	public static <E> void putData(String key,List<E> beans){
		caches.put(key, new DataBag<E>(System.currentTimeMillis(), beans));
	}

	private static class DataBag<E> {
		private long lastModifyTime;
		private List<E> beans;

		public DataBag(long lastModifyTime, List<E> beans) {
			super();
			this.lastModifyTime = lastModifyTime;
			this.beans = beans;
		}

		public boolean isExpired() {
			if (System.currentTimeMillis() - lastModifyTime > PropKit
					.getLong(Consts.ATTR_KEY_INIT_DATA_OUTTIME, Consts.DEFAULT_INIT_DATA_OUTTIME)) {
				return true;
			}
			return false;
		}

		public List<E> getBeans() {
			return beans;
		}

	}
}
